from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime

from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime
from sqlalchemy.orm import sessionmaker


engine = create_engine("mysql+pymysql://root@localhost:3306/platform")
Session = sessionmaker(bind=engine)
session = Session()

try:
    connection = engine.connect()
    print("数据库连接成功！")
    connection.close()
except Exception as e:
    print(f"数据库连接失败：{e}")


Base = declarative_base()


class Weibo(Base):
    __tablename__ = "weibo"

    id = Column(Integer, primary_key=True)
    title = Column(String(50))
    content = Column(String(1000))
    tags = Column(JSON)
    image_path = Column(String(255))
    publish_time = Column(DateTime)


Base.metadata.create_all(engine)


def save_weibo(title, content, tags, image_path):
    weibo = Weibo(
        title=title,
        content=content,
        tags=tags,
        image_path=image_path,
        publish_time=datetime.now(),
    )
    session.add(weibo)
    session.commit()


